import { createPage, base, high, ajax, cardCache, getMultiLang, pageTo, toast } from 'nc-lightapp-front';
import requestApi from './requestApi';
import 'ssccommon/components/globalPresetVar';
import { setTableGroupExtendCol, setTableExtendCol } from 'ssccommon/components/bill';
import getDefDataFromMeta from 'ssccommon/utils/getDefDataFromMeta';
import tableExtendButtonClick from './events/tableExtendButtonClick';
import { setPageStatus } from 'ssccommon/utils/statusController';
import {zzhllxLogic} from './utils'
import { viewModel } from 'nc-lightapp-front';
let { setGlobalStorage, getGlobalStorage, removeGlobalStorage } = viewModel;


//import buttonTpl from './buttonTpl';


let { NCPopconfirm } = base;
let { updateCache } = cardCache;

const { Refer } = high,
    { getRefer } = Refer; // 获取公共参照的方法
let pagecode = '';
let appcode = '';
window.presetVar = {
    ...window.presetVar,
    head: {
        head1: 'head',
        head2: ''
    },
    body: {
        body1: 'jk_busitem',
        body2: 'er_bxcontrast'
    }
};

let pageButton = presetVar.pageButton;
const statusVar = presetVar.status;
let buttonTpl = ''
let pageStatus = '';
let that = null;
let multiLangjson = {};
export default function (props) {
    appcode = (props.getUrlParam("appcode") == undefined || props.getUrlParam("appcode") == '') ? props.getSearchParam("c") : props.getUrlParam("appcode");
    pagecode = (props.getUrlParam("pagecode") == undefined || props.getUrlParam("pagecode") == '') ? props.getSearchParam("p") : props.getUrlParam("pagecode");
    window.presetVar.appcode = appcode == null || appcode == '' ? window.presetVar.appcode : appcode;
    window.presetVar.pagecode = pagecode == null || pagecode == '' ? window.presetVar.pagecode : pagecode;
    let _this = this;
    that = this;

    // props.setHashChangeCallback(() => {
    //     routeChange.call(that, props.meta.getMeta());
    // })

    let filenum = this.state.groupLists;
    let createUIDomPromise = new Promise((resolve, reject) => {
        props.createUIDom({}, (data) => {
            resolve(data);
        })
    });

    let getMultiLangPromise = new Promise((resolve, reject) => {
        getMultiLang({
            moduleId: 2011,
            domainName: 'erm',
            currentLocale: 'simpchn',
            callback: (json) => {
                resolve(json);
            }
        })
    });
    Promise.all([createUIDomPromise, getMultiLangPromise]).then((resultList) => {
        let data = resultList[0];
        let json = resultList[1];
         // 全局化组织汇率类型
        let zzhllxs = resultList[0].template.head.items.find((item,index) => {
            return item.attrcode === "zzhllx.rate_category"
        })
        window.presetVar.zzhllxs = zzhllxs && zzhllxs.options

        let meta = data.template;
        props.meta.setMeta(meta)
        pageStatus = props.getUrlParam('status');
        window.presetVar.pageId = meta.code;
        buttonTpl = {
            button: (data.button == null || data.button == undefined) ? [] : data.button
        }

        //找到更多下的附件按钮，增加附件数。
        buttonTpl.button.forEach((items) => {

            if (items.key == 'fileManager') {
                items.title = json['201102BCLF-0040'] + ' ' + filenum; //附件
            }
        });

        //表体注册增行后回调afterClick事件
        const funcs = {} 
        Object.values(window.presetVar.body).forEach(key => {
            funcs[`${key}_Add`] = {
                afterClick: () => {
                    console.log(key,'页签增行后回调')
                    //回调处理表体某些字段默认值
                    setDefautValueAfterBodyAdd.call(this, this.props, key)
                }
            }
        })
        window._tableButtonsClick = funcs

        //兼容应用复制用transtype
        let transtype = data.context.paramMap.transtype;
        window.presetVar.pullpagecode = data.context.paramMap.pullpagecode;
        if (props.getUrlParam('isinit') === true) {
            that.setState({ transtype_name: json['201102JCLF_C-0005'] });
        } else {
            this.setState({ transtype_name: data.context.paramMap.transtype_name });
        }

        window.presetVar.tradetype = props.getUrlParam("tradetype") == null || props.getUrlParam("tradetype") == '' ? transtype : props.getUrlParam("tradetype");
        window.presetVar.openbillid = props.getUrlParam("id") || ''
        if (pageStatus == statusVar.add && !props.getUrlParam('addType') && !props.getUrlParam('copyFromBillId') && !props.getUrlParam('isinit')) {
            let qextend = {
                transtypecode: window.presetVar.tradetype
            };
            requestApi.queryextend({
                data: qextend,
                success: (data) => {
                    let result = JSON.parse(data.data);
                    if (result.success == "true" && result.is_mactrl == 'true') {
                        // debugger
                        pageTo.specialLinkTo('/erm/expenseaccount/loanmanageForPull/card/index.html#/pull?', { isfromSsc: true, appcode: window.presetVar.appcode, pagecode: window.presetVar.pullpagecode });
                        routeChange.call(this, this.props)
                        return;
                    } else if (result.success == "false") {
                        toast({ content: result.message, color: 'warning' });
                        return;
                    }
                }
            });
        }
        let bodys = Object.keys(data.template.gridrelation);
        for (var i = 1; i <= bodys.length; i++) {
            window.presetVar.body["body" + i] = bodys[i - 1];
        }
        multiLangjson = json;
        loadBill.call(this, meta);//加载数据
        setTableGroupExtendCol(props, meta, buttonTpl.button, [], {
            "jk_busitem": {
                onButtonClick: tableExtendButtonClick.bind(this),
                copyRowWithoutCols: ['pk_busitem']
            }
        });
    }).then(() => {
        //请求附件控制状态
        requestApi.getAttachmentControlParams({
            data: { transtypecode: window.presetVar.tradetype },
            success: (data) => {
                // data.enablemodifyaccessory  审批中是否允许修改
                // data.mustuploadaccessory 是否必须上传附件
                window.presetVar.attachmentControl = {
                    modify: data.enablemodifyaccessory,
                    necessary: data.mustuploadaccessory
                }
            }
        })
    })
}

//浏览态、编辑态初始化单据信息
function loadBill(meta) {
    let props = this.props;
    pageStatus = props.getUrlParam('status');
    let redata = window.presetVar.redata == '' ? "Y" : window.presetVar.redata;
    if (pageStatus == statusVar.browse) {
        let viewbilldata = {};
        viewbilldata.openbillid = props.getUrlParam("id") || getGlobalStorage('sessionStorage', 'billid');
        render.call(this, meta, buttonTpl);
        viewbilldata.tradetype = props.getUrlParam("tradetype")
        viewbilldata.uid = getCookie("userid");//"1001Z3100000000000AE";这里以后从session中获取
        viewbilldata.pagecode = pagecode;
        viewbilldata.appcode = appcode;
        requestApi.viewBill({
            props: props,
            meta: props.meta.getMeta(),
            data: viewbilldata,
            success: (data) => {
                // 容错，防止返回数据是空
                if(!data) return
                props.form.setAllFormValue({ ['head']: data.head['head'] });
                //设置表体数据
                Object.values(presetVar.body).forEach((body) => {
                    if (data.bodys[body]) {
                        props.cardTable.setTableData(body, data.bodys[body]);
                    }
                });
                dataHandle.call(this, data.head["head"], props);

                if (data.head['head'].rows[0].values.qcbz.value) {
                    updateCache("pk_jkbx", props.getUrlParam("id"), data, "head", this.dataSource);
                    props.cardPagination.setCardPaginationId({ id: props.getUrlParam("id"), status: this.cardPagStatus.modify });
                }
                //}
            }
        });
    } else if (pageStatus === statusVar.edit) {
        //编辑单据，由于期初单据会在有id的情况下新增，因此加入status的判断
        if (props.getUrlParam("id") || props.getUrlParam("billid" ) || getGlobalStorage('sessionStorage', 'billid')) {
            
            let billdata = {};
            billdata.openbillid = props.getUrlParam("id") || getGlobalStorage('sessionStorage', 'billid');
            billdata.tradetype = props.getUrlParam("tradetype") || window.presetVar.tradetype;

            if (redata == "N" && pageStatus) {
                render.call(this, meta, buttonTpl, pageStatus);
                let bodyarr = [];
                let billdata = props.createExtCardData(pageTo.getSearchParam("p"), "head", bodyarr);
                dataHandle.call(this, billdata.head["head"], props);
                setFormEditableKeys(props)
                return;
            }
            billdata.uid = getCookie("userid");//这里以后从session中获取
                billdata.pagecode = pagecode;
                requestApi.viewBill({
                    props: props,
                    meta: props.meta.getMeta(),
                    data: billdata,
                    success: (data) => {
                        render.call(this, meta, buttonTpl, pageStatus);

                        props.form.setAllFormValue({ ['head']: data.head['head'] });
                        //设置表体数据
                        Object.values(presetVar.body).forEach((body) => {
                            if (data.bodys[body]) {
                                props.cardTable.setTableData(body, data.bodys[body]);
                            }
                        });
                        dataHandle.call(this, data.head["head"], props);
                        
                        setFormEditableKeys(props)

                        let org_currinfo = props.form.getFormItemsValue('head', 'bbhl');
                        if (org_currinfo.value != undefined && org_currinfo.value != null && parseFloat(org_currinfo.value) == parseFloat(1)) {
                            props.form.setFormItemsDisabled('head', { 'bbhl': true });
                        } else {
                            props.form.setFormItemsDisabled('head', { 'bbhl': false });
                        }

                    }
                });
        }       
    } 
    else  {
        let transferIds = props.transferTable.getTransferTableSelectedId("head");
        let addType = props.getUrlParam("addType");
        let userjson = {
            "pagecode": pagecode,
            "appcode": appcode,
            'isinit': props.getUrlParam('isinit')
        };
        userjson.addType = addType;
        if ("pull" == addType) {
            userjson.transferIds = transferIds;
        }
        let billdata = setDefData(meta);
        billdata.userjson = JSON.stringify(userjson);
        initData.call(this, meta, billdata).then(() => {
            // meta.arap_bxbusitem.status = 'edit';
            setFormEditableKeys(props)

            let org_currinfo = props.form.getFormItemsValue('head', 'bbhl');
            if (org_currinfo.value != undefined && org_currinfo.value != null && parseFloat(org_currinfo.value) == parseFloat(1)) {
                props.form.setFormItemsDisabled('head', { 'bbhl': true });
            } else {
                props.form.setFormItemsDisabled('head', { 'bbhl': false });
            }
            let copyFromBillId = props.getUrlParam('copyFromBillId');
            let param = {};
            param.copyFromBillId = copyFromBillId;
            param.tradetype = props.getUrlParam("tradetype") || window.presetVar.tradetype;
            param.pagecode = pagecode;
            //单据复制
            if (copyFromBillId) {
                requestApi.copyBill({
                    data: param,
                    success: (data) => {
                        props.form.setAllFormValue({ ['head']: data.head['head'] });
                        //设置表体数据

                        Object.values(presetVar.body).forEach((body) => {
                            if (data.bodys[body]) {
                                props.cardTable.setTableData(body, data.bodys[body]);
                            } else {
                                props.cardTable.setTableData(body, { rows: [] });
                            }
                        });
                        dataHandle.call(this, data.head["head"], props);
                        
                        setFormEditableKeys(props)

                        let org_currinfo = props.form.getFormItemsValue('head', 'bbhl');
                        if (org_currinfo.value != undefined && org_currinfo.value != null && parseFloat(org_currinfo.value) == parseFloat(1)) {
                            props.form.setFormItemsDisabled('head', { 'bbhl': true });
                        } else {
                            props.form.setFormItemsDisabled('head', { 'bbhl': false });
                        }
                        this.accessorybillid = '';

                        const headData = data.head['head']
                        requestApi.getAttachmentControlParams({
                            data: { transtypecode: window.presetVar.tradetype },
                            success: (data) => {
                                // data.enablemodifyaccessory  审批中是否允许修改
                                // data.mustuploadaccessory 是否必须上传附件
                                window.presetVar.attachmentControl = {
                                    modify: data.enablemodifyaccessory,
                                    necessary: data.mustuploadaccessory
                                }
                                dataHandle.call(this, headData, props);
                            }
                        })
                    }
                });
            }
            else if (props.getUrlParam('status') === 'add' && addType != "pull") {
                // props.cardTable.addRow('jk_busitem', undefined, undefined, false);
            }
        });
    }
}
export { loadBill }

function setFormEditableKeys(props) {
    //新增汇率适配逻辑，业务单据中的币种与组织本币一致时，汇率及汇率类型不可修改
    let currentrow_bzbm = props.form.getFormItemsValue('head','bzbm');
    //组织汇率类型
    let rate_category =  props.form.getFormItemsValue('head','zzhllx.rate_category'); 
    zzhllxLogic(currentrow_bzbm,rate_category,'head',props,'bbhl')

    let paytarget = props.form.getFormItemsValue("head", ['paytarget']) == null ? "" : props.form.getFormItemsValue("head", ['paytarget'])[0].value//收款对象
    if (paytarget == "0") {
        props.form.setFormItemsDisabled("head", { 'hbbm': true, 'customer': true, 'hbbm_v': true, 'customer_v': true, "custaccount": true, 'receiver': false, 'custaccount': true, 'freecust': true });
    } else if (paytarget == "1") {
        props.form.setFormItemsDisabled("head", { 'receiver': true, 'customer': true, 'hbbm': false, 'customer_v': true, 'hbbm_v': false, 'custaccount': false, 'freecust': false });
    } else if (paytarget == "2") {
        props.form.setFormItemsDisabled("head", { 'hbbm': true, 'hbbm_v': true, 'receiver': true, 'customer': false, 'customer_v': false,'custaccount': false, 'freecust': true });
    }
}

function render(meta, button) {

    //设置表格扩展列
    let props = this.props;
    pageStatus = props.getUrlParam('status');
    /* if (statusVar.browse != pageStatus) {
        setTableGroupExtendCol(props, meta, button.button, [], {
            "jk_busitem" : {onButtonClick : tableExtendButtonClick.bind(this)}

        });
    } */
    if (pageStatus == statusVar.add || pageStatus == statusVar.edit) {
        buttonTpl.button.map((btg) => {
            if (btg.key == 'buttonGroup2' && btg.children != null) {
                btg.children.map((btn) => {
                    if (btn.key == 'billSubmit') {
                        props.button.setMainButton([pageButton.billSubmit], false);
                        btn['title'] = multiLangjson['2011-0019'];  //保存提交
                    }
                })
            }
        })
    } else {
        buttonTpl.button.map((btg) => {
            if (btg.key == 'buttonGroup2' && btg.children != null) {
                btg.children.map((btn) => {
                    if (btn.key == 'billSubmit') {
                        props.button.setMainButton([pageButton.billSubmit], true);
                        btn['title'] = multiLangjson['2011-0014'];  //提交
                    }
                })
            }
        })
    }
    //按钮存入组件
    //注意：以后按钮模板的获取需要用 props.createUIDom 替代。
    props.button.hideButtonsByAreas(window.presetVar.head.head1);
    props.button.setButtons(buttonTpl.button);
    // let  filenum=this.state.groupLists;
    // getMultiLang({moduleId: 2011, domainName: 'erm',currentLocale: 'zh-CN', callback: (json) => {
    //     props.button.setButtonTitle('fileManager', json['201102BCLF-0040'] + ' ' +filenum); //附件
    //     //table扩展按钮弹窗确认框设置
    //     //props.button.setPopContent(body1 + areaBtnAction.del,'确认要删除该信息吗？') /* 设置操作列上删除按钮的弹窗提示 */
    // }})
    props.meta.addMeta(meta);

    // setTableGroupExtendCol.bind(this)(props, meta, buttonTpl.button, [], {})

    // console.log(99999, buttonTpl.button);

    //肩部按钮可见状态：页面和表格的肩部按钮，这里逻辑根据实际业务实现。
    let btnsVisibleObj = {};

    let isAddOrEditStatus = pageStatus == statusVar.edit || pageStatus == statusVar.add;
    let isBrowseStatus = pageStatus == statusVar.browse || typeof(pageStatus) == 'undefined';


    for (let btnKey in pageButton) {
        btnsVisibleObj[btnKey] = false;
    }
    let scene = props.getUrlParam('scene');
    if (isAddOrEditStatus) { //添加或编辑态 隐藏下列按钮
        btnsVisibleObj[pageButton.pageSave] = true;
        if (!(scene == 'approve' || scene == 'zycl' || scene == 'zycx' || scene == 'approvesce' || scene == 'bzcx' || scene == 'fycx')) {
            btnsVisibleObj[pageButton.billSubmit] = true;
        }      
        btnsVisibleObj[pageButton.fileManager] = true;
        btnsVisibleObj['jk_busitem_Add'] = true;
        btnsVisibleObj[pageButton['linkVoucher']] = false;
        btnsVisibleObj[pageButton['linkBudget']] = false;
        //新增态时取消按钮显示
        //if(pageStatus == statusVar.add)
        btnsVisibleObj['pageCancel'] = true;
        if (props.getUrlParam('isinit') === true) {
            btnsVisibleObj[pageButton.billSubmit] = false;
        }
        btnsVisibleObj['More'] = false;
        btnsVisibleObj['qry_loan'] = true;
    }
    if (isBrowseStatus) { //浏览态 隐藏下列按钮
        btnsVisibleObj[pageButton.pageEdit] = true;
        btnsVisibleObj[pageButton.pageCopy] = true;
        btnsVisibleObj[pageButton.pageDel] = true;
        btnsVisibleObj[pageButton.pagePrint] = true;
        btnsVisibleObj[pageButton.imageShow] = true;
        btnsVisibleObj[pageButton.imageUpload] = true;
        btnsVisibleObj[pageButton.billView] = true;
        btnsVisibleObj[pageButton['linkVoucher']] = false;
        btnsVisibleObj[pageButton['linkBudget']] = false;
        btnsVisibleObj['pageCancel'] = false;
    }
    buttonTpl.button.map((one) => {
        if (one.area.indexOf('card_body') > -1 && isBrowseStatus) {
            if (!(one.area.indexOf('card_body_inner') > -1 && one.key.indexOf('_Edit') > -1)) {
                btnsVisibleObj[one.key] = false;
            }
        }
        if (one.area.indexOf('card_body') > -1 && isAddOrEditStatus) {
            if (!(one.area.indexOf('card_body_inner') > -1 && one.key.indexOf('_Edit') > -1)) {
                btnsVisibleObj[one.key] = true;
            }
        }
    });

    props.button.setButtonsVisible(btnsVisibleObj);


    switch (pageStatus) {
        case statusVar.edit:
        case statusVar.add:
            // props.form.setFormStatus('head', 'edit');
            // Object.values(window.presetVar.body).forEach((body)=>{
            //     props.editTable.setStatus(body, 'edit');
            // });
            {
                let ls_bodys = [];
                Object.values(window.presetVar.body).forEach((body) => {
                    ls_bodys.push(body);
                });
                setPageStatus(props, meta, ['head'], ls_bodys, 'edit');
            }
            break;
        case statusVar.browse:
            {
                let ls_bodys = [];
                Object.values(window.presetVar.body).forEach((body) => {
                    ls_bodys.push(body);
                });
                setPageStatus(props, meta, ['head'], ls_bodys, 'browse');
            }
            break;
    }

}
export { render }

function initData(meta, billdata) {
    let props = this.props;
    function isEmptyRow(rows) {
        let isEmp = false
        const firstRow = rows.rows[0] ||{}
        if(Object.keys(firstRow.values).every(v => firstRow.values[v].value == undefined)){
            isEmp = true
        }
        return isEmp
    }
    return new Promise((resolve, reject) => {
        // TOP NCCLOUD-91597 校验报销标准取模板时需要使用模板ID chengwbc ADD
        billdata.templetid = meta.pageid;
        // BTM NCCLOUD-91597 校验报销标准取模板时需要使用模板ID
        requestApi.loaddata({
            meta: meta,
            props: props,
            data: billdata,
            success: (data) => {
                meta['head'].status = statusVar.add;
                render.call(this, meta, buttonTpl);
                if (props.getUrlParam('status') === 'add') {
                    props.form.setAllFormValue({ ['head']: data.head['head'] });
                    Object.values(presetVar.body).forEach((body) => {
                        if (data.bodys[body] && !isEmptyRow(data.bodys[body])) {
                            // props.cardTable.setTableData(body, data.bodys[body]);
                        }
                    });
                } else if ( props.getUrlParam('addType') == "pull" || props.getUrlParam('addType') == undefined ) {
                    props.form.setAllFormValue({ ['head']: data.head['head'] });
                    //设置表体数据
                    Object.values(presetVar.body).forEach((body) => {
                        if (data.bodys[body]) {
                            props.cardTable.setTableData(body, data.bodys[body]);
                        }
                    });
                    dataHandle.call(this, data.head['head'], props);
                    setPageStatus(props, meta, ['head'],  Object.values(presetVar.body), 'edit');
                }
                // if (props.getUrlParam('status') !== 'add' && props.getUrlParam('addType') == "pull" || props.getUrlParam('addType') == undefined ) {
                //     props.form.setAllFormValue({ ['head']: data.head['head'] });
                //     //设置表体数据
                //     Object.values(presetVar.body).forEach((body) => {
                //         if (data.bodys[body]) {
                //             props.cardTable.setTableData(body, data.bodys[body]);
                //         }
                //     });
                //     dataHandle.call(this, data.head['head'], props);
                //     setPageStatus(props, meta, ['head'],  Object.values(presetVar.body), 'edit');
                // }
                let qcbz = data.head['head'].rows[0].values.qcbz.value//是否期初
                //期初单据新增态清空  修改态不清空
                if (qcbz && props.getUrlParam('status') === 'add') {
                    this.setState({ showBack: false });
                    props.form.setAllFormValue({ ['head']: data.head['head'] });
                    Object.values(presetVar.body).forEach((body) => {
                        props.cardTable.setTableData(body, { rows: [] });
                    });
                }
                // resolve();
            
                let validBodyArray = [];
                Object.values(presetVar.body).forEach((one)=>{
                   if (data.bodys[one]){
                        let temp = {
                            "tablecode" : one,
                            "tabledata" : data.bodys[one]
                        }
                        validBodyArray.push(temp);
                   }
                })
                
                //表头可编辑字段控制
                setFormEditableKeys(props)

                //拉单生成的报销单明细需要控制收款对象相关字段的可编辑性
                validBodyArray.forEach(validBody => {
                    let tablecode = validBody.tablecode;
                    let rows = props.cardTable.getAllRows(tablecode)
                    if (rows){
                        rows.forEach(row => {
                            let currentrow_paytarget = props.form.getFormItemsValue("head", ['paytarget']) == null ? "" : props.form.getFormItemsValue("head", ['paytarget'])[0].value//收款对象
                            if (currentrow_paytarget){
                                let currentrow_paytargetvalue = currentrow_paytarget.value
                                //控制表体收款对象相关字段的可编辑性
                                let editablekeys = []
                                let uneditablekeys = []
                                if ("0" == currentrow_paytargetvalue){
                                    editablekeys = ['receiver','skyhzh']
                                    uneditablekeys = ['hbbm','hbbm_v','customer','customer_v','custaccount']
                                }else if("1" == currentrow_paytargetvalue){
                                    editablekeys = ['hbbm','hbbm_v','custaccount']
                                    uneditablekeys = ['receiver','skyhzh','customer','customer_v']
                                }else if("2" == currentrow_paytargetvalue){
                                    editablekeys = ['customer','customer_v','custaccount']
                                    uneditablekeys = ['receiver','skyhzh','hbbm','hbbm_v']
                                }
                                props.cardTable.setEditableByRowId(tablecode, row.rowid, editablekeys, true)
                                props.cardTable.setEditableByRowId(tablecode, row.rowid, uneditablekeys, false)
                            }
                        })
                    }
                    
                })
                
                resolve();
            }
        });
    });

}

function setDefData(meta) {
    return getDefDataFromMeta(meta, 'nc.vo.ep.bx.JKHeaderVO');
}
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return "";
}
export { getCookie }

// 1903方式，参数列表在url中，改为根据url的page属性从session中获取
// function getRequest1(url) {
//     if (!url)
//         url = document.location.search;
//     var theRequest = new Object();
//     if (url.indexOf("?") != -1) {
//         var str = url.substring(url.indexOf("?") + 1);
//         var strs = str.split("&");
//         for (var i = 0; i < strs.length; i++) {
//             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
//         }
//     }
//     return theRequest;
// }
// xuzd5 适配到1909
function getRequest1(url) {
    if (!url)
        url = document.location.search;
    let sessionInfo = ""
    if (url.indexOf("page=") != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf("?") != -1) {
            var str = url.substring(url.indexOf("?") + 1);
            var strs = str.split("&");
            page = strs[0].split("=")[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf("?") != -1) {
        sessionInfo = url.substring(url.indexOf("?") + 1);
    } else {
        sessionInfo = url;
    }


    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split("&");
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
    return theRequest;
}
export { getRequest1 }

function getRequestString(name) {
    if (getRequest1()[name] != undefined) {
        return getRequest1()[name];
    }
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
function dataHandle(head, props) {
    const that = this;
    //处理数据和按钮状态
    if (head == null || head.rows[0] == null || head.rows[0].values == null)
        return;
    let scene = props.getUrlParam('scene');
    let deal = props.getUrlParam('deal');
    let sxbz = head.rows[0].values.sxbz.value;//单据生效状态
    let spzt = head.rows[0].values.spzt.value;//审批状态
    let djzt = head.rows[0].values.djzt.value//单据状态
    let qcbz = head.rows[0].values.qcbz.value//是否期初
    let btnsVisibleObj = {};
    pageStatus = props.getUrlParam('status');
    
    let isAddOrEditStatus =  pageStatus ? (pageStatus == statusVar.edit || pageStatus == statusVar.add) : true //pageStatus&&pageStatus == statusVar.edit || pageStatus == statusVar.add;
    //返回期初按钮是否显示
    if (qcbz === true) {
        if (isAddOrEditStatus) {
            this.setState({ showBack: false });
        } else {
            if (scene != "fycx" && scene != "bzcx" && scene != "bz" && scene != 'lc') {
                this.setState({ showBack: true });
            }
        }
    }
    if (isAddOrEditStatus) {
        if (qcbz === true || props.getUrlParam('isinit') === true) {
            props.button.setButtonsVisible({
                [pageButton.billSubmit]: false
            });
            this.setState({ pageInfoShow: false });//编辑态隐藏翻页
            that && that.setState({uploaderBtnDisable: false})
        }
        if (spzt == 2 || spzt == 3) {
            if (window.presetVar.attachmentControl) {
                that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
            }
        } else if(spzt == -1) {
            //单据不在审批中,默认可修改
            that && that.setState({uploaderBtnDisable: false})
        }
        return;
    }

    let isBrowseStatus = pageStatus == statusVar.browse
    for (let btnKey in pageButton) {
        btnsVisibleObj[btnKey] = false;

        //来源于审批人门户、作业处理时 显示 ：修改、影像扫描|影像查看、联查预算、联查凭证、更多（联查审批情况、联查单据、附件、关闭/重启、打印）
        // debugger;
        if (scene == 'approve' || scene == 'zycl' || scene == 'approvesce') {
            if ((btnKey == pageButton.pageEdit || btnKey == pageButton.imageShow || btnKey == pageButton.imageUpload || btnKey == pageButton.pagePrint || btnKey == pageButton.linkQueryFysq || btnKey == pageButton.linkQueryJkbx || btnKey == pageButton.billApprove || btnKey == pageButton.fileManager))
                btnsVisibleObj[btnKey] = isBrowseStatus;
        }
        //来源于作业查询时 显示 ：影像查看、联查预算、联查凭证、更多（联查审批情况、联查单据、打印）
        else if ((scene == 'zycx' || scene == 'bzcx' || scene == 'fycx')) {
            if ((btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint || btnKey == pageButton.linkQueryFysq || btnKey == pageButton.linkQueryJkbx || btnKey == pageButton.billApprove || btnKey == pageButton.fileManager))
                btnsVisibleObj[btnKey] = isBrowseStatus;
        } else {
            //审批状态为初始态，显示：修改|删除|复制、提交、影像扫描|影像查看、更多（附件、作废、打印）
            if (spzt == "-1" && (btnKey == pageButton.pagePrint || btnKey == pageButton.fileManager || btnKey == pageButton.pageCopy || btnKey == pageButton.imageShow || btnKey == pageButton.imageUpload || btnKey == pageButton.billSubmit || btnKey == pageButton.billInvalid || btnKey == pageButton.pageEdit || btnKey == pageButton.pageDel)) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
            //审批状态为提交态，显示：复制、收回、影像扫描|影像查看、更多（联查审批情况、附件、打印）
            else if ((spzt == "3" || spzt == "2") && (btnKey == pageButton.pagePrint || btnKey == pageButton.fileManager || btnKey == pageButton.pageCopy || btnKey == pageButton.imageShow || btnKey == pageButton.imageUpload || btnKey == pageButton.billApprove)) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
            //审批状态为通过态，显示：复制、影像查看、更多（联查审批情况、联查单据、附件、关闭/重启、打印）
            else if (spzt == "1" && (btnKey == pageButton.pageCopy || btnKey == pageButton.fileManager || btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint || btnKey == pageButton.linkQueryFysq || btnKey == pageButton.linkQueryJkbx || btnKey == pageButton.billApprove)) {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            }
        }

        //已提交显示收回按钮
        if (btnKey == pageButton.billRecall && !(scene == 'approve' || scene == 'zycl' || scene == 'zycx' || scene == 'approvesce' || scene == 'bzcx' || scene == 'fycx')) {
            if (spzt == "3") {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
        //已完成单据，隐藏影像扫描，附件管理
        // if (btnKey == pageButton.imageUpload||btnKey == pageButton.fileManager){
        if (btnKey == pageButton.imageUpload) {
            if (spzt === '1') {
                btnsVisibleObj[btnKey] = false;
            } else {
                if (scene != 'zycx' && scene != 'bzcx' && scene != 'fycx') {
                    btnsVisibleObj[btnKey] = isBrowseStatus;
                }
            }
        }

        //已完成单据显示联查功能
        if (btnKey == pageButton.linkQueryJkbx) {
            if (sxbz == "1") {
                btnsVisibleObj[btnKey] = true;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
        //审批中心或作业平台打开
        if (btnKey == "linkVoucher" || btnKey == "linkBudget") {
            if (scene == 'approve' || scene == 'approvesce' || scene == 'zycl' || scene == 'zycx' || scene == 'bzcx' || scene == 'fycx') {
                btnsVisibleObj[pageButton['linkVoucher']] = true;
                btnsVisibleObj[pageButton['linkBudget']] = true;
            } else {
                btnsVisibleObj[pageButton['linkVoucher']] = false;
                btnsVisibleObj[pageButton['linkBudget']] = false;
            }
        }

        //作废的单据影藏保存提交修改等状态
        if (djzt == "-1") {
            if ( btnKey == pageButton.pageCopy || btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint) {
                btnsVisibleObj[btnKey] = true;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }


    }
    if(spzt=='1'){
        btnsVisibleObj["pageMakebill"] = true;//审批中心的制单按钮 
        btnsVisibleObj[pageButton.pageEdit] = false;
    }
    //审批结束后附件不可修改
     if (spzt == 1) {
        that&&that.setState({uploaderBtnDisable: true})
      } 
      // 审批进行中  提交状态 附件可编辑受控
    if (spzt == 2 || spzt == 3) {
        if (window.presetVar.attachmentControl) {
            that && that.setState({uploaderBtnDisable: !window.presetVar.attachmentControl.modify})
        }
    } else if(spzt == -1) {
        //单据不在审批中,默认可修改
        that && that.setState({uploaderBtnDisable: false})
    }

    //任务处理除待处理外其他的单据不允许修改
    if (deal != undefined && (deal == 'handon' || deal == 'adjust' || deal == 'sscreject' || deal == 'handled')) {
        btnsVisibleObj[pageButton.pageEdit] = false;
    }
    if (!isAddOrEditStatus) {
        btnsVisibleObj['linkQueryFysq'] = true;
    }
    if (isAddOrEditStatus) {
        btnsVisibleObj["More"] = false;
    }
    if (qcbz === true) {
        btnsVisibleObj[pageButton.linkQueryFysq] = false;
        btnsVisibleObj[pageButton.billApprove] = false;
        btnsVisibleObj[pageButton.fileManager] = true;//期初借款浏览态需要放出附件按钮
        if (scene != "bzcx" && scene != "fycx" && scene != "bz" && scene != 'lc') {
            btnsVisibleObj['pageAdd'] = true;
            btnsVisibleObj[pageButton.pageEdit] = true;
            btnsVisibleObj[pageButton.pageDel] = true;
            btnsVisibleObj[pageButton.imageUpload] = isBrowseStatus;
            this.setState({ pageInfoShow: true })//浏览态显示翻页
        }
    }

    btnsVisibleObj['qry_loan'] = true
    //来源于报表联查的单据
    if (scene == 'sscermlink' || scene == "linksce") {
        for (let btnKey in pageButton) {
            if (btnKey == pageButton.imageShow || btnKey == pageButton.pagePrint || btnKey == pageButton.fileManager || btnKey == "linkVoucher" || btnKey == "linkBudget") {
                btnsVisibleObj[btnKey] = isBrowseStatus;
            } else {
                btnsVisibleObj[btnKey] = false;
            }
        }
    }
    if(scene =='bzcx') {
        btnsVisibleObj['qry_loan'] = false  //暂时处理,联查不显示借款情况
        if( djzt == '-1' ) {
            btnsVisibleObj[pageButton.pageCopy] = false
        }
    }
    props.button.setButtonsVisible(btnsVisibleObj);
}
export { dataHandle }

//期初借款专用方法，浏览期初借款并更新缓存
function viewInitBill(id) {
    let props = this.props;
    let viewbilldata = {};
    viewbilldata.openbillid = id;
    viewbilldata.tradetype = props.getUrlParam("tradetype");
    viewbilldata.uid = getCookie("userid");//"1001Z3100000000000AE";这里以后从session中获取
    viewbilldata.pagecode = pagecode;
    viewbilldata.appcode = appcode;
    requestApi.viewBill({
        props: props,
        meta: props.meta.getMeta(),
        data: viewbilldata,
        success: (data) => {
            props.form.setAllFormValue({ ['head']: data.head['head'] });
            //设置表体数据
            Object.values(presetVar.body).forEach((body) => {
                if (data.bodys[body]) {
                    this.props.cardTable.setTableData(body, data.bodys[body]);
                }
            });
            dataHandle.call(this, data.head["head"], props);
            //if(pageStatus == statusVar.browse){
            let ls_bodys = [];
            Object.values(window.presetVar.body).forEach((body) => {
                ls_bodys.push(body);
            });
            setPageStatus(props, props.meta.getMeta(), ['head'], ls_bodys, 'browse');
            updateCache("pk_jkbx", id, data, "head", this.dataSource);
            props.cardPagination.setCardPaginationId({ id, status: this.cardPagStatus.modify });
            props.setUrlParam({ 'id': id });
        }
    });
}
export { viewInitBill }

//路由变化监听函数，location.hash及linkTo,pushTo都会调用
function routeChange(props) {
    let pageStatus = props.getUrlParam('status');
    window.presetVar.pagestatus = pageStatus;
    let meta = props.meta.getMeta();
    if (location.href.indexOf('initbills') > -1) {    //url是期初借款的情况
        //期初借款卡片内点新增、修改、复制等按钮需要调loadbill，但点返回期初列表按钮时不需要调，因此还是需要分开处理
        if (this.props.getUrlParam('isinit')) {
            loadBill.call(this, meta);
        }
    } else {  //非期初借款
        loadBill.call(this, meta);
    }
}
export { routeChange }


function setDefautValueAfterBodyAdd(props, tablecode) {
    const moudleid = tablecode;
    const multiLang = props.MutiInit.getIntl(2011);

    //rowIndex不能使用getAllRows,要使用getVisibleRows,前者会带出删除的行,在删除行再新增的情况下，rowIndex计算错误
    let rowIndex = props.cardTable.getVisibleRows(moudleid).length - 1;

    let keys = ['bzbm','dwbm','deptid','jkbxr','paytarget','receiver','skyhzh','hbbm','customer','hbbm_v','customer_v','custaccount','bbhl','groupbbhl','globalbbhl','zzhllx','zzhllyrq']
    let default_values = {}
    keys.forEach(key => {
        let headvalue = props.form.getFormItemsValue(window.presetVar.head.head1,key);
        default_values[key] = headvalue
    })
    props.cardTable.setValByKeysAndIndex(moudleid, rowIndex, default_values)

    let paytarget = props.cardTable.getDataByIndex(moudleid, rowIndex).values['paytarget'].value
    let nullvalue = {
        display: null,
        value : null
    }

    // 增行时，本币汇率、汇率类型、汇率来源日期，需根据表头来设置表体其编辑性
    let bbhlFlag = props.form.getFormItemsDisabled('head', 'bbhl'); //表头本币汇率编辑性
    let zzhllxFlag = props.form.getFormItemsDisabled('head', 'zzhllx'); //表头本币汇率类型编辑性
    let zzhllyrqFlag = props.form.getFormItemsDisabled('head', 'zzhllyrq'); //表头本币汇率日期编辑性
    // 表头中本币种、汇率类型更改后，表体中本币汇率、汇率类型、汇率来源日期需同时控制其编辑性
    let editkeys = []
    let unedikeys = []
    bbhlFlag ? unedikeys.push('bbhl') : editkeys.push('bbhl')
    zzhllxFlag ? unedikeys.push('zzhllx') : editkeys.push('zzhllx')
    zzhllyrqFlag ? unedikeys.push('zzhllyrq') : editkeys.push('zzhllyrq')
    props.cardTable.setEditableByIndex(moudleid, rowIndex, editkeys, true)
    props.cardTable.setEditableByIndex(moudleid, rowIndex, unedikeys, false)

    //新增行时，清理掉与收款对象不匹配的其他字段的默认值
    if (paytarget == '0'){
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'hbbm',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'customer',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'custaccount',nullvalue)
        props.cardTable.setEditableByIndex(moudleid, [rowIndex], ['hbbm','hbbm_v','customer','customer_v','custaccount'], false)
    }else if (paytarget == '1'){
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'receiver',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'customer',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'skyhzh',nullvalue)
        props.cardTable.setEditableByIndex(moudleid, [rowIndex], ['receiver','customer','customer_v','skyhzh'], false)
    }else if (paytarget == '2'){
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'receiver',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'hbbm',nullvalue)
        props.cardTable.setValByKeyAndIndex(moudleid,rowIndex,'skyhzh',nullvalue)
        props.cardTable.setEditableByIndex(moudleid, [rowIndex], ['receiver','hbbm','hbbm_v','skyhzh'], false)
    }
}
export { setDefautValueAfterBodyAdd }